const fs = require("fs");
const qiniu = require("qiniu");
const co = require("co");
const OSS = require("ali-oss");
const COS = require("cos-nodejs-sdk-v5");
import { QI_NIU, ALI_CLIENT, TX_CLIENT } from "../config/index";
/**
 * 上传到七牛云
 * @param buffer 文件可读流
 * @param fileName 文件名称
 * @returns
 */
export function upToQiNiu(buffer: any, fileName: string) {
  const accessKey = QI_NIU.accessKey;
  const secretKey = QI_NIU.secretKey;
  const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

  const options = {
    scope: QI_NIU.bucket,
  };
  const putPolicy = new qiniu.rs.PutPolicy(options);

  const uploadToken = putPolicy.uploadToken(mac);
  // Zone_z0 华东机房  Zone_z1 华北机房  Zone_z2 华南机房   Zone_na0 北美
  const config = new qiniu.conf.Config();
  config.zone = qiniu.zone.Zone_z2;
  // config.zone = qiniu.zone.Zone_z2
  const localFile = buffer;
  const formUploader = new qiniu.form_up.FormUploader(config);
  const putExtra = new qiniu.form_up.PutExtra();
  // 文件上传
  return new Promise((resolved, reject) => {
    formUploader.putStream(
      uploadToken,
      fileName,
      localFile,
      putExtra,
      function (respErr: any, respBody: any, respInfo: any) {
        if (respErr) {
          reject(respErr);
        } else {
          resolved(respBody);
        }
      }
    );
  });
}

/**
 * 上传到阿里云oss
 * @param filePath  路径（如果本地文件完整路径）
 * @param fileName  存在oss名称，可不带后缀(可以设置路径)
 */
export function upToAliOss(filePath: string, fileName: any) {
  const client = new OSS({
    region: ALI_CLIENT.region,
    accessKeyId: ALI_CLIENT.accessKeyId,
    accessKeySecret: ALI_CLIENT.accessKeySecret,
    bucket: ALI_CLIENT.bucket,
  });
  return new Promise((resolve, reject) => {
    //ali-oss
    co(function* (): any {
      client.useBucket(ALI_CLIENT.bucket); //自定义项
      var result = yield client.put(fileName, filePath);
      //var result = yield client.put(fields.store, new Buffer(fields.buffer));
      resolve(result);
    }).catch((error: Error) => {
      reject(error);
    });
  });
}

/**
 *
 * @param buffer 文件流
 * @param fileName  文件名称(可带路径)
 * @returns
 */
export function upToTxCos(buffer: any, fileName: any) {
  const cos = new COS({
    SecretId: TX_CLIENT.SecretId, // 密钥id
    SecretKey: TX_CLIENT.SecretKey, // 密钥key
  });
  return new Promise((resolve, reject) => {
    cos.putObject(
      {
        Bucket: TX_CLIENT.Bucket,
        Region: TX_CLIENT.Region,
        Key: fileName, //文件名称
        Body: buffer, // 文件流
      },
      function (err: Error, data: any) {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      }
    );
  });
}
